import React, { useState, useEffect } from "react";
import { View, SafeAreaView } from "react-native";
import { WebView } from "react-native-webview";
import { WebViewScreenProps } from "../../types/NavigationTypes";
import { WebViewNativeProgressEvent } from "react-native-webview/lib/WebViewTypes";
import { ProgressView } from "@react-native-community/progress-view";

const WebViewScreen: React.FC<WebViewScreenProps> = ({ navigation, route }) => {
  const { title, url } = route.params as { title: string; url: string };

  const [progress, setProgress] = useState(0);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    navigation.setOptions({
      title: title
    });
  }, [navigation]);

  const handleLoadStart = () => {
    setProgress(0);
    setIsLoaded(false);
  };

  const handleLoadEnd = () => {
    setProgress(1);
    setIsLoaded(true);
  };

  const handleLoadProgress = ({
    nativeEvent,
  }: {
    nativeEvent: WebViewNativeProgressEvent;
  }) => {
    setProgress(nativeEvent.progress);
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 }}>
        {!isLoaded && (
          <ProgressView
            progress={progress}
            style={{ height: 5, width: "100%" }}
            progressTintColor="#3BC859"
            trackTintColor="white"
          />
        )}
        <WebView
          source={{ uri: url }}
          onLoadStart={handleLoadStart}
          onLoadProgress={handleLoadProgress}
          onLoadEnd={handleLoadEnd}
          style={{ flex: 1 }}
        />
      </View>
    </SafeAreaView>
  );
};

export default WebViewScreen;
